/**
 * @author 艾尼亚尔
 * @date 2025/8/18
 * @description websocket
 */
import {config} from "@/config";

type  WsData = Record<string, unknown> | string;

interface Socket {
  websocket: WebSocket | null;
  init: (e: WsData, callback: (data: WsData) => void) => void;
  send: (e: WsData) => void;
  handleMessage: (event: MessageEvent, callback: (data: WsData) => void) => void; // 新增
}

const socket: Socket = {
  websocket: null,
  init: (e: WsData, callback: (data: WsData) => void) => {
    const ws_url: string = `${config.WS_URL}/ws`;
    socket.websocket = new WebSocket(ws_url);

    // 连接成功时发送初始数据
    socket.websocket.onopen = () => {
      socket.send(e)
    };

    // 统一用 handleMessage 处理消息
    socket.websocket.onmessage = (event: MessageEvent) => {
      socket.handleMessage(event, callback);
    };

    // 监听WS服务器连接断开状态
    socket.websocket.onclose = () => {
      console.log("WS服务器连接断开！");
    };
  },
  /**
   * 发送数据
   * @param data 要发送的数据
   */
  send(data: WsData) {
    if (socket.websocket) {
      socket.websocket.send(JSON.stringify(data));
    } else {
      console.error("WebSocket is not initialized.");
    }
  },
  /**
   * 内部方法：统一处理消息
   * @param event 消息事件
   * @param callback 回调函数
   */
  handleMessage(event: MessageEvent, callback: (data: WsData) => void) {
    if (event.data === 'ping') {
      // 心跳响应
      socket.send('pong');
    } else {
      // 业务数据处理
      const data = JSON.parse(event.data);
      // 调用回调函数
      callback(data);
    }
  },
};

export default socket;
